package com.zkq.graduate.runner;

import com.zkq.graduate.pojo.Permission;
import com.zkq.graduate.pojo.Role;
import com.zkq.graduate.service.PermissionService;
import com.zkq.graduate.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zhangkaiqiang
 * @Date 2019/12/1  13:38
 * @Description TODO
 * 在项目启动后把role和权限的关联关系加载到redis中进行保存,方便后面使用
 */
@Component
@Slf4j
public class SetRoleAndPermissionToRedisRunner implements CommandLineRunner {

	@Resource
	private RedisTemplate redisTemplate;

	@Resource(name = "permissionService")
	private PermissionService permissionService;

	@Resource(name = "roleService")
	private RoleService roleService;

	@Override
	public void run(String... args) throws Exception {
		log.info("加载角色-权限到redis中进行保存");

		// 得到所有的角色
		List<Role> roleList=roleService.listAllRole();

		Map<String,List<Permission>> roleAndPermissionMap=new LinkedHashMap<>();
		roleList.forEach((item)->{
			String roleName=item.getRoleName();
			// 根据每个角色,得到该角色拥有的所有的权限
			if(StringUtils.isNotBlank(roleName)){
				List<Permission> permissionList= permissionService.listAllPermission(String.valueOf(item.getId()));
				// 把角色--权限的对应关系保存到map中
				roleAndPermissionMap.put(roleName,permissionList);
				log.info(roleName+">>>>>>对应的权限保存到redis完成");
			}
		});

		// 保存到redis,加快系统速度
		redisTemplate.opsForHash().putAll("roleAndPermission",roleAndPermissionMap);
		log.info("加载角色-权限到redis中完成");
	}
}
